package com.yzk.auction.controller;

import com.alibaba.fastjson.JSON;
import com.yzk.auction.dao.UsersDao;
import com.yzk.auction.entity.*;
import com.yzk.auction.service.GoodsService;
import com.yzk.auction.service.OrderSerivce;
import com.yzk.auction.service.SecondCategoryService;
import com.yzk.auction.utils.PageModel;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * Author: 园中葵小组成员
 * Description:后台管理功能controller
 */
@WebServlet(name = "management",urlPatterns = "/management")
public class ManagementController extends HttpServlet {
    private GoodsService goodsService = new GoodsService();
    private static final long serialVersionUID = 1L;
    UsersDao usersDao = new UsersDao();
    private Users users;
    //日期格式化
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //通过method参数区分不同的操作
        String method = request.getParameter("method");
        if(method.equals("ulist")){//分页查询用户列表
            this.ulist(request,response);
        }else if(method.equals("udelete")){//删除用户信息
            this.udelete(request,response);
        }else if(method.equals("ushow_update")) {//显示用户更新页面
            this.uShowUpdatePage(request,response);
        }else if(method.equals("uupdate")) {//用户更新方法
            this.uupdate(request,response);
        }else if(method.equals("glist")){//分页查询商品列表
            this.glist(request,response);
        }else if(method.equals("gdelete")){//删除商品信息
            this.gdelete(request,response);
        }else if(method.equals("gshow_update")) {//显示商品更新页面
            this.gShowUpdatePage(request,response);
        }else if(method.equals("gupdate")) {//商品更新方法
            this.gupdate(request,response);
        }else if(method.equals("gshow_create")) {//显示商品新增页面
            this.gShowCreatePage(request,response);
        }else if(method.equals("gcreate")) {//商品新增方法
            this.gcreate(request, response);
        }else if(method.equals("clist")){//分页查询分类列表
            this.clist(request,response);
        }else if(method.equals("cdelete")){//删除分类信息
            this.cdelete(request,response);
        }else if(method.equals("cshow_update")) {//显示分类更新页面
            this.cShowUpdatePage(request,response);
        }else if(method.equals("cupdate")) {//分类更新方法
            this.cupdate(request,response);
        }else if(method.equals("cshow_create")) {//显示分类新增页面
            this.cShowCreatePage(request,response);
        }else if(method.equals("ccreate")) {//分类新增方法
            this.ccreate(request, response);
        }else if(method.equals("olist")){//分页查询订单列表
            this.olist(request,response);
        }else if(method.equals("odelete")){//删除订单信息
            this.odelete(request,response);
        }else if(method.equals("oshow_update")) {//显示订单更新页面
            this.oShowUpdatePage(request,response);
        }else if(method.equals("oupdate")) {//订单更新方法
            this.oupdate(request,response);
        }else if(method.equals("gsecond")){//二级联动查找二级分类
            this.findSecondById(request,response);
        }
    }

    /**
     * 分页查询用户列表
     * @param request
     * @param response
     */
    private void ulist(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        List<Users> usersList = usersDao.getList();
        request.setAttribute("usersList", usersList);
        request.getRequestDispatcher("WEB-INF/jsp/ulist.jsp").forward(request, response);
    }
    /**
     * 删除用户信息
     * @param request
     * @param response
     */
    private void udelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_id = request.getParameter("user_id");
        int result = usersDao.udelete(user_id);
        List<Users> usersList = usersDao.getList();
        if(result!=0){
            //request.setAttribute("list", user);
            request.setAttribute("usersList", usersList);
            request.getRequestDispatcher("WEB-INF/jsp/ulist.jsp").forward(request, response);
        }else{
            request.setAttribute("error", "error");
            request.getRequestDispatcher("WEB-INF/jsp/infox.jsp").forward(request, response);
        }
    }
    /**
     * 显示用户更新页面
     * @param request
     * @param response
     */
    private void uShowUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_id = request.getParameter("user_id");
        Users user = usersDao.getone(user_id);
        System.out.println(user);
        if(user!=null){
            request.setAttribute("user", user);
            request.getRequestDispatcher("WEB-INF/jsp/update.jsp").forward(request, response);
        }else{
            request.setAttribute("error", "error");
            request.getRequestDispatcher("WEB-INF/jsp/infox.jsp").forward(request, response);
        }
    }
    /**
     * 用户更新方法
     * @param request
     * @param response
     */
    private void uupdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_id = request.getParameter("user_id");
        String user_name = request.getParameter("user_name");
        String user_pwd = request.getParameter("user_pwd");
        String user_sex = request.getParameter("user_sex");
        String user_salary = request.getParameter("user_salary");
        String user_tel = request.getParameter("user_tel");
        String user_addr = request.getParameter("user_addr");
        System.out.println(user_id);
        System.out.println(user_name);
        System.out.println(user_pwd);
        System.out.println(user_sex);
        System.out.println(user_salary);
        System.out.println(user_tel);
        System.out.println(user_addr);
        int result = usersDao.uupdate(user_id,user_name,user_pwd,user_sex,user_salary,user_tel,user_addr);
        if(result!=0){
            List<Users> usersList = usersDao.getList();
            request.setAttribute("usersList",usersList);
            request.getRequestDispatcher("WEB-INF/jsp/ulist.jsp").forward(request, response);
        }else{
            request.setAttribute("error", "error");
            request.getRequestDispatcher("WEB-INF/jsp/infox.jsp").forward(request, response);
        }
    }
    /**
     * 分页查询商品列表
     * @param request
     * @param response
     */
    private void glist(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String p = request.getParameter("p");
        String r = request.getParameter("r");
        if(p == null) {
            p = "1";
        }
        if(r == null) {
            r = "6";
        }
        PageModel pageModel = goodsService.pagination(Integer.parseInt(p),Integer.parseInt(r));
        System.out.println(pageModel);
        request.setAttribute("pageModel", pageModel);
        request.getRequestDispatcher("WEB-INF/jsp/glist.jsp").forward(request,response);
    }
    /**
     * 删除商品信息
     * @param request
     * @param response
     */
    private void gdelete(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        PrintWriter out = response.getWriter();
        try {
            goodsService.delete(Integer.parseInt(id));
            //{“result”:“ok”}
            out.println("{\"result\":\"ok\"}");
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //{“result”:e.getMessage()}
            out.println("{\"result\":\""+e.getMessage()+"\"}");
        }
    }
    /**
     * 显示商品更新页面
     * @param request
     * @param response
     */
    private void gShowUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String gid = request.getParameter("gid");
        GoodsDTO goodsDTO = goodsService.findGoodsById(Integer.parseInt(gid));
        request.setAttribute("goodsDTO",goodsDTO);
        List<FirstCategory> firstCategory = goodsService.findAllFirstCategory();
        for(FirstCategory f:firstCategory){
            System.out.println(f);
        }
        request.setAttribute("fCategory",firstCategory);
        request.getRequestDispatcher("WEB-INF/jsp/gupdate.jsp").forward(request,response);
    }
    /**
     * 商品更新方法
     * @param request
     * @param response
     */
    private void gupdate(HttpServletRequest request,HttpServletResponse response){
        int isPictureModified = 0;
        //1.初始化FileUpload组件
        FileItemFactory factory = new DiskFileItemFactory();
        /**
         * FileItemFactory用于将前端表单的数据转换为一个个FileItem对象
         * ServletFileUpload则是为FileUpload组件提供Java Web的Http请求解析
         */
        ServletFileUpload sf = new ServletFileUpload(factory);
        //2.遍历所有FileItem
        try {
            List<FileItem> formData = sf.parseRequest(request);
            GoodsDTO goodsDTO = new GoodsDTO();
            for(FileItem fi:formData) {
                if(fi.isFormField()) {
                    System.out.println("普通输入项："+fi.getFieldName()+":"+fi.getString("UTF-8"));
                    switch (fi.getFieldName()) {
                        case "goods_name":
                            goodsDTO.setGoods_name(fi.getString("UTF-8"));
                            break;
                        case "first_cid":
                            goodsDTO.setFirst_cid(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "second_cid":
                            goodsDTO.setSecond_cid(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "start_time":
                            String start = fi.getString("UTF-8");
                            //String转java.util.Date
                            java.util.Date udStartTime = null;
                            udStartTime = sdf.parse(start);
                            goodsDTO.setStart_time(udStartTime);
                            break;
                        case "end_time":
                            String end = fi.getString("UTF-8");
                            //String转java.util.Date
                            java.util.Date udEndTime = null;
                            udEndTime = sdf.parse(end);
                            goodsDTO.setEnd_time(udEndTime);
                            break;
                        case "low_price":
                            goodsDTO.setLow_price(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "price_markup":
                            goodsDTO.setPrice_markup(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "appraisal_price":
                            goodsDTO.setAppraisal_price(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "goods_desc":
                            goodsDTO.setGoods_desc(fi.getString("UTF-8"));
                            break;
                        case "id":
                            goodsDTO.setGoods_id(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "isPictureModified":
                            isPictureModified = Integer.parseInt(fi.getString("UTF-8"));
                            break;
                        default:
                            break;
                    }
                }else {
                    if(isPictureModified == 1) {
                        System.out.println("文件上传项："+fi.getFieldName());
                        //3.文件保存到服务器目录
                        String path = request.getServletContext().getRealPath("/upload");//获取Tomcat在实际运行环境下对应的目录的物理地址
                        System.out.println("文件上传目录："+path);
                        //String fileName = "test.jpg";
                        //UUID根据计算机的本地特性生生成唯一的字符串
                        String fileName = UUID.randomUUID().toString();
                        //扩展名：
                        //fi.getName()得到原始文件名，截取最后一个.后所有字符串，例如wxml.jpg->.jpg
                        String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
                        fi.write(new File(path,fileName + suffix));
                        goodsDTO.setGoods_picture("/upload/" + fileName + suffix);
                    }
                }
            }
            goodsService.gupdate(goodsDTO,isPictureModified);
            response.sendRedirect("/management?method=glist");//返回列表页
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 显示商品新增页面
     * @param request
     * @param response
     */
    private void gShowCreatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        List<FirstCategory> firstCategory = goodsService.findAllFirstCategory();
        request.setAttribute("firstCategory",firstCategory);
        request.getRequestDispatcher("WEB-INF/jsp/gcreate.jsp").forward(request,response);
    }
    /**
     * 商品新增方法
     * @param request
     * @param response
     */
    private void gcreate(HttpServletRequest request,HttpServletResponse response){

        //1.初始化FileUpload组件
        FileItemFactory factory = new DiskFileItemFactory();
        /**
         * FileItemFactory用于将前端表单的数据转换为一个个FileItem对象
         * ServletFileUpload则是为FileUpload组件提供Java Web的Http请求解析
         */
        ServletFileUpload sf = new ServletFileUpload(factory);
        //2.遍历所有FileItem
        try {
            List<FileItem> formData = sf.parseRequest(request);
            GoodsDTO goodsDTO = new GoodsDTO();
            for(FileItem fi:formData) {
                System.out.println(fi.getFieldName());
                if(fi.isFormField()) {
                    System.out.println("普通输入项："+fi.getFieldName()+":"+fi.getString("UTF-8"));
                    switch (fi.getFieldName()) {
                        case "goods_name":
                            goodsDTO.setGoods_name(fi.getString("UTF-8"));
                            break;
                        case "first_cid":
                            goodsDTO.setFirst_cid(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "second_cid":
                            goodsDTO.setSecond_cid(Integer.parseInt(fi.getString("UTF-8")));
                            break;
                        case "start_time":
                            String start = fi.getString("UTF-8");
                            String startStr = start.substring(0,10)+" "+start.substring(11,16)+":00";
                            //String转java.util.Date
                            java.util.Date udStartTime = null;
                            udStartTime = sdf.parse(startStr);
                            goodsDTO.setStart_time(udStartTime);
                            break;
                        case "end_time":
                            String end = fi.getString("UTF-8");
                            String endStr = end.substring(0,10)+" "+end.substring(11,16)+":00";
                            //String转java.util.Date
                            java.util.Date udEndTime = null;
                            udEndTime = sdf.parse(endStr);
                            goodsDTO.setEnd_time(udEndTime);
                            break;
                        case "low_price":
                            goodsDTO.setLow_price(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "price_markup":
                            goodsDTO.setPrice_markup(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "appraisal_price":
                            goodsDTO.setAppraisal_price(Double.parseDouble(fi.getString("UTF-8")));
                            break;
                        case "goods_desc":
                            goodsDTO.setGoods_desc(fi.getString("UTF-8"));
                            break;
                        default:
                            break;
                    }
                }else {
                    System.out.println("文件上传项："+fi.getFieldName());
                    //3.文件保存到服务器目录
                    String path = request.getServletContext().getRealPath("/upload");//获取Tomcat在实际运行环境下对应的目录的物理地址
                    System.out.println("文件上传目录："+path);
                    //UUID根据计算机的本地特性生生成唯一的字符串
                    String fileName = UUID.randomUUID().toString();
                    //扩展名：
                    //fi.getName()得到原始文件名，截取最后一个.后所有字符串，例如wxml.jpg->.jpg
                    String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
                    fi.write(new File(path,fileName + suffix));
                    goodsDTO.setGoods_picture("/upload/" + fileName + suffix);
                }
            }
            int num = -1;
            num = goodsService.createGoods(goodsDTO);
            response.sendRedirect("/management?method=glist");//返回商品列表页
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 根据一级分类id，获取二级分类
     * @param request
     * @param response
     */
    private void findSecondById(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        List<SecondCategory> secondCategory = goodsService.findSecondById(Integer.parseInt(id));
        String json = JSON.toJSONString(secondCategory);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(json);
    }
    /**
     * 分页查询分类列表
     * @param request
     * @param response
     */
    private void clist(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        try {

            String p = request.getParameter("p");
            String r = request.getParameter("r");
            if(p == null) {
                p = "1";
            }
            if(r == null) {
                r = "6";
            }

            //1、查询所有学生
            SecondCategoryService service = new SecondCategoryService();
            PageModel pageModel = service.findSecondCategoryAll(Integer.parseInt(p),Integer.parseInt(r));
            //2、把数据存储到缓存域中
            request.setAttribute("pageModel",pageModel);
            //3、跳转页面
            request.getRequestDispatcher("WEB-INF/jsp/clist.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 删除分类信息
     * @param request
     * @param response
     */
    private void cdelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        try {
            //1、获取要删除的id
            int second_cid = Integer.parseInt(request.getParameter("second_cid"));
            //2、执行删除操作
            SecondCategoryService service = new SecondCategoryService();
            service.deleteSecondCategory(second_cid);
            //3、跳转页面
            request.getRequestDispatcher("management?method=clist").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 显示分类更新页面
     * @param request
     * @param response
     */
    private void cShowUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        try {
            //1、接收id
            int second_cid = Integer.parseInt(request.getParameter("second_cid"));
            //2、、查询学生数据
            SecondCategoryService service = new SecondCategoryService();
            Category category = service.findfindSecondCategoryById(second_cid);
            //3、将查询的数据放到缓存域中
            request.setAttribute("stu",category);
            //4、跳转页面
            request.getRequestDispatcher("WEB-INF/jsp/cupdate.jsp").forward(request,response);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 分类更新方法
     * @param request
     * @param response
     */
    private void cupdate(HttpServletRequest request,HttpServletResponse response){
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            //1、获取客户端提交上来的数据
            int second_cid = Integer.parseInt(request.getParameter("second_cid"));
            String second_cname = request.getParameter("second_cname");
            String first_cname = request.getParameter("first_cname");
            //2、更新数据到数据库
            SecondCategoryService service = new SecondCategoryService();
            //获取一级分类的id
            int first_cid = service.findfindSecondCategoryByName(first_cname);
            SecondCategory category = new SecondCategory(second_cid,second_cname,first_cid);
            //更新数据库数据
            service.updateSecondCategory(category);
            //3、跳转页面
            request.getRequestDispatcher("management?method=clist").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 显示分类新增页面
     * @param request
     * @param response
     */
    private void cShowCreatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //跳转页面
        request.getRequestDispatcher("WEB-INF/jsp/ccreate.jsp").forward(request,response);
    }
    /**
     * 分类新增方法
     * @param request
     * @param response
     */
    private void ccreate(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        try {
            //1、获取客户端输入的数据
            String second_cname = request.getParameter("second_cname");
            String first_cname = request.getParameter("first_cname");
            System.out.println("***");
            System.out.println(second_cname);
            System.out.println(first_cname);
            //2、将数据添加到数据库
            SecondCategoryService service = new SecondCategoryService();
            //获取一级分类的id
            int first_cid = service.findfindSecondCategoryByName(first_cname);
            SecondCategory secondCategory = new SecondCategory(second_cname,first_cid);
            //插入到数据库
            service.insertSecondCategory(secondCategory);
            //跳转页面
            request.getRequestDispatcher("management?method=clist").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 分页查询订单列表
     * @param request
     * @param response
     */
    private void olist(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        List<OrderAll> list = null;
        list = OrderSerivce.listOrder();
        request.setAttribute("orderList",list);
        request.getRequestDispatcher("WEB-INF/jsp/olist.jsp").forward(request,response);
    }
    /**
     * 删除订单信息
     * @param request
     * @param response
     */
    private void odelete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String order_id = request.getParameter("order_id");
        int result = OrderSerivce.odelete(order_id);
        List<OrderAll> list = OrderSerivce.listOrder();
        if(result!=0){
            request.setAttribute("orderList",list);
            request.getRequestDispatcher("WEB-INF/jsp/olist.jsp").forward(request,response);
        }else{
            request.getRequestDispatcher("WEB-INF/jsp/olist.jsp").forward(request,response);
        }
    }
    /**
     * 显示订单更新页面
     * @param request
     * @param response
     */
    private void oShowUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String user_name = request.getParameter("user_name");
        String user_addr = request.getParameter("user_addr");
        int result = 0;
        result = OrderSerivce.oupdate(user_name,user_addr);
        List<OrderAll> list = OrderSerivce.listOrder();
        if(result!=0){
            request.setAttribute("orderList",list);
            request.getRequestDispatcher("WEB-INF/jsp/olist.jsp").forward(request,response);
        }else{
            request.getRequestDispatcher("WEB-INF/jsp/olist.jsp").forward(request,response);
        }
    }
    /**
     * 订单更新方法
     * @param request
     * @param response
     */
    private void oupdate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String order_id =request.getParameter("order_id");
        int id = Integer.parseInt(order_id);
        List<OrderAll> list = OrderSerivce.listOrder();
        OrderAll changeOrder = null;
        for (OrderAll order:list
        ) {
            if (order.getOrder_id()==id){
                changeOrder=order;
            }
        }
        request.setAttribute("changeOrder",changeOrder);
        request.getRequestDispatcher("WEB-INF/jsp/oupdate.jsp").forward(request,response);
    }
}
